package com.itheima.health.task;

import com.itheima.health.business.ReportBusiness;
import com.itheima.health.common.ReportConst;
import com.itheima.health.service.ReportService;
import com.itheima.health.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 统计分析定时任务
 */
@Slf4j
@Component
public class ReportTask {
    @Autowired
    private ReportBusiness reportBusiness;

    /**
     * 每月28号凌晨2点，定时更新会员统计数据
     * 每天2点，定时更新会员统计数据
     */
    @Scheduled(cron = "0 0 2 28 * ?")
    public void updateMemberReport(){
        log.info("定时任务，更新会员统计数据");
        // 获取12个月前的月末
        LocalDate date = DateTimeUtil.getLastDateBeforeMonths(LocalDate.now(),
                ReportConst.MONTH_TWELVE);
        for (int i = 0; i < ReportConst.MONTH_TWELVE; i++) {
            String month = DateTimeUtil.format(date, ReportConst.PATTERN_YEAR_MONTH);
            // 更新该月的会员总数
            reportBusiness.getCountByMonth(month);
            date = date.plusMonths(1);
        }
    }

}
